package droid.frame.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * 可缩放的ImageView<br>
 * 控件大小根据显示图片的原始长宽等比例缩放, 高度按照宽度缩放
 * 
 * @author coffee
 * 
 *         2014年1月13日下午1:49:55
 */
@SuppressLint("AppCompatCustomView")
public class ScaledImageView extends ImageView {

	/**
	 * 相对于宽度的百分比<br>
	 * 1表示高度与宽度等值, 0.5表示高度是宽度的一半
	 */
	private String hint;

	private int viewWidth = 0;//
	private int viewHeight = 0;

	public ScaledImageView(Context context) {
		super(context);
	}

	public ScaledImageView(Context context, AttributeSet attrs) {
		super(context, attrs);

		int[] attrsArray = new int[] { android.R.attr.id, // 0
				android.R.attr.hint // 1
		};
		TypedArray ta = context.obtainStyledAttributes(attrs, attrsArray);
		// 关闭硬件加速。否则会报OpenGLRenderer Message：Cannot generate texture from bitmap
		// setLayerType(View.LAYER_TYPE_SOFTWARE, null);
		hint = ta.getString(1);
		if (hint == null) {
			hint = "1";
		}
		ta.recycle();
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));
		// 原始图片的真实尺寸
		viewWidth = getMeasuredWidth();
		viewHeight = (int) (viewWidth * Float.valueOf(hint));
		if (viewWidth == 0) {
			// widthMeasureSpec = MeasureSpec.makeMeasureSpec(viewWidth, MeasureSpec.AT_MOST);
		} else {
			widthMeasureSpec = MeasureSpec.makeMeasureSpec(viewWidth, MeasureSpec.EXACTLY);
		}
		// 精确计算高度
		heightMeasureSpec = MeasureSpec.makeMeasureSpec(viewHeight, MeasureSpec.EXACTLY);
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}
}
